<template>
  <div class="app-container">
    <!-- 工具栏 -->
    <div class="tool-bar-container">
      <span class="current-area-text">当前定值区：{{ currentAreaDisplay }}</span>
      <el-button
        :type="isEditMode ? 'warning' : 'primary'"
        :icon="isEditMode ? 'search' : 'refresh'"
        @click="onEditModeBtnClick"
      >
        {{ isEditMode ? "修改禁用" : "修改使能" }}
      </el-button>
      <el-button
        v-if="isEditMode"
        type="success"
        icon="search"
        :disabled="!hasChanges"
        @click="handleSaveChanges"
      >
        写入到IDE
      </el-button>
      <el-button type="info" icon="refresh" @click="handleRefresh">刷新数据</el-button>
      <el-button type="success" icon="search" @click="handleExportAll">导出全部</el-button>
    </div>
    <el-card shadow="hover" class="data-table">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        class="data-table__content"
      >
        <template v-for="(ruleColumn, index) in tableRuleColumns" :key="index">
          <el-table-column
            v-if="isEditMode && ruleColumn.key === 'newValue'"
            :label="ruleColumn.label"
            align="left"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <template v-if="row.type === 'enum'">
                <el-select v-model="row.newValue" @change="() => handleValueChange(row)">
                  <el-option
                    v-for="option in row.options"
                    :key="option"
                    :label="option"
                    :value="option"
                  />
                </el-select>
              </template>
              <template v-else-if="row.type === 'number'">
                <el-input
                  v-model="row.newValue"
                  type="number"
                  @blur="($event) => (row.newValue = parseFloat(row.newValue))"
                  :step="row.step"
                  :min="row.min"
                  :max="row.max"
                  @input="() => handleValueChange(row)"
                />
                <!-- <div
                  v-if="row.newValue < row.min || row.newValue > row.max"
                  style="color: red; font-size: 12px"
                >
                  请输入介于 {{ row.min }} 和 {{ row.max }} 之间的数值
                </div> -->
              </template>
              <template v-else-if="row.type === 'string'">
                <el-input v-model="row.newValue" @input="() => handleValueChange(row)" />
              </template>
            </template>
          </el-table-column>
          <el-table-column
            v-else
            :prop="ruleColumn.key"
            :label="ruleColumn.label"
            align="left"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <span>{{ formatCellValue(row, ruleColumn) }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <offset-pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:offset="queryParams.offset"
        v-model:limit="queryParams.limit"
        @pagination="fetchData"
      />
      <el-dialog v-model="dialogVisible" append-to-body>
        <span>有未保存的更改，确定要退出编辑模式吗？</span>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmExitEditMode">确定</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "BatchUpdate",
  inheritAttrs: false,
});
import { useRoute } from "vue-router";
import { useAppStore, useHmiConfigStore, useCommonApiStore, useAreaSettingStore } from "@/store";
import type { TableHeaderRule, ColumnRule } from "@/api/hmi/config.api";
import type { CommonHmiDataOffsetPageQuery } from "@/api/hmi/common-hmi-data.api";
import { formatBatchUpdateTableData, formatCellValue } from "@/utils/hmi-data-table";

// store 实例
const route = useRoute();
const appStore = useAppStore();
const hmiConfigStore = useHmiConfigStore();
const commonApiStore = useCommonApiStore();
const areaSettingStore = useAreaSettingStore();

// 响应式数据
const apiPath = ref<string>("");
// const apiPath = computed(() => {
//   // 兼容 meta.params.api 可能为字符串或对象
//   const metaApi = route?.meta?.params?.api;
//   if (typeof metaApi === "string") return metaApi;
//   if (metaApi && typeof metaApi === "object" && "value" in metaApi) return metaApi.value;
//   return "";
// });
const tableData = ref<any[]>([]);
const tableHeaders = ref<any[]>([]);
const total = ref<number>(0);
const isEditMode = ref<boolean>(false);
const hasChanges = ref<boolean>(false);
const changeHistory = reactive<Map<number, { oldValue: any; newValue: any }>>(new Map());
const loading = ref<boolean>(false);
const dialogVisible = ref<boolean>(false);
const isBatchUpdate = ref<boolean>(false);

// 查询参数，严格类型
const queryParams = reactive<CommonHmiDataOffsetPageQuery>({
  offset: 0,
  limit: 10,
  keywords: "",
  fixedValueArea: 0,
  createTime: ["", ""],
});

// 当前定值区
const currentArea = ref<number | null>(null);
const currentAreaDisplay = computed(() => {
  if (!currentArea.value) {
    return "全部";
  }
  return currentArea.value === 0 ? "全部" : currentArea.value;
});

// 规则列
const tableRuleColumns = ref<ColumnRule[]>([]);
const curTableRule = ref<TableHeaderRule | null>(null);

// 通用数据获取
async function fetchData() {
  if (!apiPath.value) return;
  loading.value = true;
  try {
    const ret_api_data = await commonApiStore.fetchList(apiPath.value, { ...queryParams });
    total.value = +ret_api_data.total;
    const { tableHeaders: newTableHeaders, tableData: newTableData } = formatBatchUpdateTableData(
      ret_api_data.list,
      tableRuleColumns.value
    );
    tableHeaders.value = newTableHeaders;
    tableData.value = newTableData;
  } catch (error) {
    console.error("获取数据失败", error);
  } finally {
    loading.value = false;
  }
}

// 复用：重置与查询
function handleQuery() {
  queryParams.offset = 0;
  fetchData();
}
const handleResetQuery = handleQuery;

// 编辑模式切换
function onEditModeBtnClick() {
  if (isEditMode.value && hasChanges.value) {
    dialogVisible.value = true;
  } else {
    toggleEditMode();
  }
}
function toggleEditMode() {
  isEditMode.value = !isEditMode.value;
  if (!isEditMode.value) {
    hasChanges.value = false;
    changeHistory.clear();
  }
}
function confirmExitEditMode() {
  dialogVisible.value = false;
  toggleEditMode();
  fetchData();
}

// 复用：值变更处理
function handleValueChange(row: any) {
  if (row.newValue !== row["IED Value"]) {
    changeHistory.set(row.id, {
      oldValue: row["IED Value"],
      newValue: row.newValue,
    });
  } else {
    changeHistory.delete(row.id);
  }
  hasChanges.value = changeHistory.size > 0;
}

// 复用：保存
async function handleSaveChanges() {
  if (!hasChanges.value) {
    ElMessage.warning("没有需要保存的更改");
    return;
  }
  loading.value = true;
  try {
    const changes = Array.from(changeHistory.entries()).map(([id, change]) => ({
      id,
      ...tableData.value.find((item) => item.id === id),
      "IED Value": change.newValue,
    }));
    await commonApiStore.batchUpdate(apiPath.value, changes);
    ElMessage.success("保存成功");
    toggleEditMode();
    fetchData();
  } catch (error: any) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败：" + (error.message || "未知错误"));
  } finally {
    loading.value = false;
  }
}

// 复用：刷新
function handleRefresh() {
  fetchData();
}

// 复用：导出（可扩展）
async function handleExportAll() {
  // TODO: 导出逻辑
  ElMessage.info("导出功能待实现");
}

// 动态输入组件类型
function getInputComponent(row: any) {
  if (row.type === "enum") return "el-select";
  if (row.type === "number") return "el-input";
  if (row.type === "string") return "el-input";
  return "el-input";
}
function getInputProps(row: any) {
  if (row.type === "enum") {
    return {
      options:
        row.options?.map((option: any) => ({ key: option, label: option, value: option })) || [],
      placeholder: "请选择",
    };
  }
  if (row.type === "number") {
    return {
      type: "number",
      step: row.step,
      min: row.min,
      max: row.max,
    };
  }
  return {};
}

function updateTableRuleAndFetchData(api: string) {
  // const headerRule = hmiConfigStore.getTableHeaderRuleByUri(api);
  const headerRule = hmiConfigStore.getTableHeaderRuleByPath(route.path);
  if (headerRule) {
    curTableRule.value = headerRule;
    tableRuleColumns.value =
      headerRule.columns?.slice().sort((a, b) => (a.index ?? 0) - (b.index ?? 0)) || [];
  } else {
    curTableRule.value = null;
    tableRuleColumns.value = [];
  }
  fetchData();
}

onMounted(async () => {
  // initBatchUpdate();
  try {
    apiPath.value = route?.meta?.params?.api || "";
    await hmiConfigStore.initHmiConfig();
    if (apiPath.value) {
      updateTableRuleAndFetchData(apiPath.value);
    }
  } catch (error) {
    console.error("初始化配置失败:", error);
  }
});

// apiPath 根据 route?.meta?.params?.api; 计算得到
// 监听 apiPath 变化，只有当前页面激活时，才执行 updateTableRuleAndFetchData 函数，进行更新
const isPageActive = ref(true); // 添加页面激活状态标识

onActivated(() => {
  isPageActive.value = true;
});

onDeactivated(() => {
  isPageActive.value = false;
});

// 监听 API 变化
watch(
  () => apiPath.value,
  (oldApi, newApi) => {
    console.log(
      "batch-update oldApi",
      oldApi,
      "newApi",
      newApi,
      "isPageActive",
      isPageActive.value
    );
    if (newApi && isPageActive.value) {
      console.log("batch-update updateTableRuleAndFetchData", newApi);
      updateTableRuleAndFetchData(newApi);
    }
  }
  // { immediate: true }
);

// 监听定值区变化
watch(
  () => areaSettingStore.currentArea,
  (newValue) => {
    currentArea.value = newValue;
    queryParams.fixedValueArea = newValue || 0;
    fetchData();
  }
  // { immediate: true }
);
</script>
